<template>
  <!-- 文件管理器 auth：weilan time：2019-10-25 github：https://github.com/hql7 -->
  <div class="wl-explorer" v-loading="loading" element-loading-text="数据加载中"
    element-loading-background="rgba(0, 0, 0, 0.5)">
    <!-- 头部按钮区 -->
    <el-form class="wl-header-btn" :inline="true" size="medium" @submit.native.prevent>
      <!-- 基本操作 -->
      <el-form-item>
        <el-button type="primary" @click="handleFolder('add')">新增文件夹</el-button>
        <!-- <el-button type="primary">test</el-button> -->
        <el-button :disabled="file_checked_data.length!=1||!file_checked_data[0].is_folder"
          @click="handleFolder('edit')">编辑文件夹</el-button>
        <el-button type="danger" size="medium" @click="handleDel">删除</el-button>
        <el-button @click="handleFolder('addfile')">上传文件</el-button>
        <el-button plain :disabled="file_checked_data.length==0" type="primary" @click="handleFolder('moving')">移动
        </el-button>
        <!-- solt自定义头部按钮区 -->
        <slot name="header-btn"></slot>
      </el-form-item>
      <!-- 基本操作 -->
      <!-- 展示形式 -->
      <el-form-item class="u-right">
        <i class="iconfont icon-wl-list file-show-type" v-show="layout.show_list"
          @click="layout.show_list=!layout.show_list"></i>
        <i class="iconfont icon-wl-grid file-show-type" v-show="!layout.show_list"
          @click="layout.show_list=!layout.show_list"></i>
      </el-form-item>
      <!-- 展示形式 -->
    </el-form>
    <!--文件路径操作区-->
    <el-form :inline="true" size="medium" :model="file" class="wl-header-file" @submit.native.prevent>
      <!-- 路径搜索 -->
      <!-- {{}} -->
      <el-form-item class="file-path-box">
        <el-autocomplete class="u-full" ref="file-path-ipt" placeholder="请输入文件路径" disabled v-model="file.path"
          @keyup.enter.native="filePathChange" @select="filePathChange" :fetch-suggestions="pathQuerySearch">
          <img slot="prefix" class="file-path-img" src="./images/folder@3x.png" alt="文件夹" title="文件夹" />
        </el-autocomplete>
      </el-form-item>
      <!-- 路径搜索 -->
      <!-- 关键字搜索 -->
      <el-form-item class="file-search-box" style="width:250px">
        <el-input v-model="file.key" placeholder="请输入关键字搜索" @keyup.enter.native="getFileList('find')">
          <el-button slot="append" icon="el-icon-search file-search" @click="getFileList('find')"></el-button>
        </el-input>
      </el-form-item>
      <!-- 关键字搜索 -->
      <!-- 向前向后 -->
      <el-form-item style="width: 120px;display: flex;">
        <i class="iconfont icon-wl-left file-path-handle" :class="{'u-disabled':pathIsStart}"
          @click="pathBtn('prv')"></i>
        <i class="iconfont icon-wl-right file-path-handle" :class="{'u-disabled':pathIsEnd}"
          @click="pathBtn('next')"></i>
        <i class="iconfont icon-wl-up file-path-handle" :class="{'u-disabled':pathIsStart}" @click="pathBtn('top')"></i>
      </el-form-item>
      <!-- 向前向后 -->
    </el-form>
    <!-- 主内容区 -->
    <el-scrollbar class="wl-main-scroll">
      <!-- 文件列表区 -->
      <div class="wl-main-list">
        <!-- 表格型文件列表 -->
        <el-table v-show="layout.show_list" @selection-change="filrChecked" highlight-current-row border
          :data="file_table_data" class="wl-table" ref="wl-table">
          <el-table-column align="center" type="selection" width="55"></el-table-column>
          <el-table-column align="center" type="index" label="序号" width="55"></el-table-column>
          <slot name="table-column-top"></slot>
          <el-table-column v-for="item of columnsArr" show-overflow-tooltip :key="item._id" :prop="item.prop"
            :width="item.width" :label="item.label" :align="item.align" :min-width="item.minWidth"
            :formatter="item.formatter">
            <template slot-scope="scope">
              <!-- 名称列 -->
              <div v-if="item.prop =='file_name'" @click="enterTheLower(scope.row, scope.row.is_folder)"
                class="wl-name-col wl-is-folder">
                <!-- 不同文件类型图标区 -->
                <div class="namecol-iconbox">
                  <img :src="fileTypeIcon(scope.row)" class="name-col-icon" alt="文件类型图标" />
                </div>
                <!-- 不同文件类型 显示内容-->
                <div class="namecol-textbox">
                  {{scope.row[item.prop]}}
                </div>
              </div>
              <!-- 非名称列 -->
              <template v-else>
                {{
                  item.formatter
                  ? item.formatter(scope.row, scope.column, scope.row[item.prop],scope.$index)
                  : scope.row[item.prop]
                  }}
              </template>
            </template>
          </el-table-column>
          <slot name="table-column-bottom"></slot>
        </el-table>
        <!-- 列表型文件列表 -->
        <ul class="wl-list" v-show="!layout.show_list">
          <li class="wl-list-item wl-is-folder" v-for="(item, idx) in file_table_data" :key="item.id">
            <el-checkbox class="wl-checkbox" @change="listItemCheck($event,item)" v-model="item._checked">
            </el-checkbox>
            <div @click="enterTheLower(item, item.is_folder)">
              <img :src="fileTypeIcon(item)" class="name-col-icon" alt="文件类型图标" />
              <p class="list-item-name" :title="item.file_name">
                {{
                  item.formatter
                  ? item.formatter(item, null, item.file_name, idx)
                  : item.file_name
                  }}
              </p>
            </div>
          </li>
        </ul>

      </div>
    </el-scrollbar>
    <opera-dialog ref="myoperation" v-if="modalStatus == '文件操作弹窗'"></opera-dialog>
  </div>
</template>

<script>
  import operaDialog from "./filecomponents/opera_dialog"; // 文件上传
  import {
    arrayToTree,
    downLoad
  } from "./util/myutil.js";
  export default {
    name: "wlExplorer",
    components: {
      operaDialog
    },
    data() {
      return {
        loading: false,
        //列表名称
        columnsArr: [{
            label: "名称",
            prop: "file_name",
            minWidth: 120
          },
          {
            label: "修改日期",
            align: "center",
            width: 120,
            formatter(row) {
              return row.edit_date.split("T")[0] || "-";
            }
          },
          {
            label: "类型",
            align: "center",
            width: 90,
            formatter(row) {
              return row.file_type === 1 ? "文件夹" : row.suffix_name;
            }
          },
          {
            label: "大小",
            minWidth: 90,
            align: "center",
            formatter(row) {
              if (row.file_size === null) return "-";
              if (row.file_size < 1024) {
                // 1024以下显示kb
                return row.file_size + "B";
              }
              if (row.file_size < 1024 * 1024) {
                // 1024以下显示kb
                return (row.file_size / 1024).toFixed(2) + "KB";
              }
              if (row.file_size < 1024 * 1024 * 1024) {
                // 1024*1024
                let _mb = (row.file_size / (1024 * 1024)).toFixed(2);
                return parseFloat(_mb) + "MB";
              }
              let _gb = (row.file_size / (1024 * 1024 * 1024)).toFixed(2);
              return parseFloat(_gb) + "GB";
            }
          },
          {
            label: "创建日期",
            align: "center",
            width: 120,
            formatter(row) {
              return row.create_date.split("T")[0] || "-";
            }
          },
          {
            label: "作者",
            minWidth: 100,
            align: "center",
            formatter(row) {
              return row.create_by || "-";
            }
          },
          {
            label: "描述",
            minWidth: 100,
            formatter(row) {
              return row.describe || "-";
            }
          }
        ],
        // file_table_data: [], // 当前数据
        file_checked_data: [], // 列表多选数据
        // 所有文件路径 用于文件地址输入框自动提示,如不传则使用历史记录
        allPath: [],
        layout: {
          show_list: true, // 文件展示形式
        }, // 视图管理
        file: {
          pid: "", // 父文件夹
          id: "", // 文件夹id
          path: "", // 文件路径
          key: "" // 关键字
        }, // 文件相关参数
        path: {
          level: 1, // 当前层级
          index: -1, // 在历史的第几步
          history: [{
            path: "", // 文件夹名字
            pid: "", // 路径
            id: "", // 文件夹id
            data: [] // 数据
          }] // 历史路径
        }, // 记录路径历史
      };
    },
    props: {
      file_table_data: {
        type: Array,
        default: []
      }
    },

    watch: {
      file_table_data(o, v) {
        //console.log(o)
      }
    },

    mounted() {},
    created() {
      //获取第一层
      this.getFileList("get", null)
    },
    methods: {
      /**
       * 文件夹时进入下一级-文件时预览文件
       * row: Object 行数据
       * is_folder: Boolean 行是否文件夹
       */
      enterTheLower(row, is_folder) {
        // 历史找不到子集时 请求更新
        if (is_folder == 1) {
          //为文件夹时更新
          if (this.path.history.length - 1 > this.path.index && row.id == this.path.history[this.path.index + 1].pid) {
            this.path.index++
            this.path.lever++
            this.file.pid = row.pid
            this.set_file_table_data(this.path.history[this.path.index].data)
            this.file.path = this.path.history[this.path.index].path
          } else {
            this.getFileList("get", row)
          }
        } else {
          //下载文件
          downLoad(row.file_path, row.file_name)
        }
      },

      //刷新文件列表
      refreshFileList(id = null, type = "") {
        this.getFileList("refresh", {
          id: id,
          type: type
        })
      },

      getFileList(op_type, row = null) {
        let ob = {}
        ob.op_type = op_type
        if (op_type == 'get') {
          //获取
          ob.pid = (row == null ? '' : row.id)
          ob.row = row
          ob.type = null
          ob.params = {
            pid: ob.pid
          }
        } else if (op_type == 'refresh') {
          //更新
          ob.pid = (row.id == null ? '' : row.id[0])
          ob.type = row.type
          ob.id = row.id
          ob.params = {
            pid: ob.pid
          }
        } else if (op_type == 'find') {
          //查找
          if (this.file.key == "") {
            ob.params = {
              pid: ""
            }
          } else {
            ob.params = {
              file_name: this.file.key
            }
          }
        }

        //console.log(params)
        this.$emit("getFileList", ob)
      },


      aftergetFileList(ob, res) {
        // console.log(ob, res)
        if (ob.op_type == "get") {
          //获取列表
          this.set_file_table_data(res)
          this.aftergetFile(ob.row, res)
        } else if (ob.op_type == 'refresh') {
          //刷新列表
          if (ob.type != 'moving_two') {
            //不是移动目标文件夹内容变化时
            this.set_file_table_data(res)
          }
          this.afterrefreshFlie(ob.id, ob.type, res)
        } else if (ob.op_type == 'find') {
          //查找列表
          this.set_file_table_data(res)
          this.file.path = ""
        } else if (ob.op_type == 'delete') {
          //删除列表
          this.refreshFileList([this.file.pid], "delete")
        }
      },


      //获取后台数据后的处理逻辑
      aftergetFile(row, res) {
        //console.log(row, res)
        let pid = (row == null ? '' : row.id)
        //记录访问路径
        if (row != null) {
          //字段拼接
          this.file.path += (this.file.path == '' ? '' : '\\') + row.file_name
        } else {
          this.file.path = ""
          this.path.index = -1
        }
        this.path.index++
        this.path.lever++
        this.file.pid = pid
        this.path.history[this.path.index] = {
          path: this.file.path,
          pid: pid,
          data: res
        }
        //若历史访问当前文件夹与当前不一致，则清除后面的历史记录
        if ((this.path.history.length - 1 > this.path.index) && (pid != this.path.history[this.path
            .index].pid)) {
          this.path.history = this.path.history.slice(0, this.path.index)
        }
      },

      //刷新文件列表之后的操作
      afterrefreshFlie(id, type, res) {
        //操作刷新后不记录访问路径但要修改本段路径的内容
        if (type != 'moving_two') {
          let pid = (id == null ? '' : id[0])
          let indexk = this.path.history.findIndex(item => item.pid == pid)
          //console.log(indexk)
          if (indexk != -1) {
            this.path.history[indexk].data = res
          }
          this.file.pid = pid
          if (type == 'moving') {
            //移动到的文件夹数据也要变化
            this.refreshFileList([id[1]], 'moving_two')
          } else {
            this.loading = false;
          }
        } else {
          //移动时查找移动到的位置执行的函数
          this.loading = false;
          //操作刷新后不记录访问路径但要修改本段路径的内容
          let indexk2 = this.path.history.findIndex(item => item.pid == id)
          // console.log(indexk2)
          if (indexk2 != -1) {
            this.path.history[indexk2].data = res
          }
        }

      },

      // 前进后退按钮操作
      pathBtn(type) {
        if ((type == "prv" && this.pathIsStart) || (type == "next" && this.pathIsEnd) || (type == "top" && this
            .pathIsStart)) {
          //  console.log(111)
          return
        } else {
          if (type === "prv") {
            //到上一层
            this.path.index--
            this.path.lever--
          } else if (type === "next") {
            this.path.index++
            this.path.lever++
          } else if (type === "top") {
            //到第一层
            this.path.index = 0
            this.path.lever = 1
          }

          this.set_file_table_data(this.path.history[this.path.index].data)
          this.file.path = this.path.history[this.path.index].path
          this.file.pid = this.path.history[this.path.index].pid
        }
      },

      /**
       * 文件夹编辑操作
       * type: string 添加add 编辑edit  上传文件addfile 
       * auth: boolean 是否只修改权限
       */
      handleFolder(type) {
        this.$store.commit('updateModalStatus', '文件操作弹窗')
        this.$store.commit('showModal', true)
        this.$nextTick(function () {
          this.$refs.myoperation.openFunction(type, this.file_checked_data)
        })
      },
      // 文件夹删除操作
      handleDel() {
        if (this.file_checked_data.length > 0) {
          this.$confirm(
              "确认删除选中的" +
              this.file_checked_data.length +
              "项?",
              "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
              }
            )
            .then(() => {
              this.loading = true;
              let params = {};
              params.ids = this.commonV.deveridarrry(
                this.file_checked_data
              );
              this.$emit("handleDel", params)
            })
            .catch(() => {});
        } else {
          this.$message({
            message: "请至少选择一个项目",
            type: "warning"
          });
        }
      },

      //获取所有的文件夹,编辑和筛选的时候
      getAllFolders(params) {
        this.loading = true;
        let allparams = {
          params: params,
          api: 'fileMangement',
        }
        this.$store
          .dispatch("getmsgData", allparams)
          .then(response => {
            this.loading = false;
            let res = response.data;
            //console.log(res)
            // let _list = res
            this.tree_folder_list = arrayToTree(_list);
            this.ruleForm.ParentId = this.$parent.file.pid
          })
          .catch(err => {
            this.loading = false;
            console.log(err);
            this.$message.error("网络连接错误" + "fileMangement");
          });
      },

      // 输入文件路径
      filePathChange(item) {
        //  console.log(item)
        let _act_item = this.path.history.find(
          i => i.pid === item.id
        );
        //console.log(_act_item)
        if (_act_item) {
          this.file.pid = _act_item.pid;
          this.set_file_table_data(_act_item.data)
        } else {
          this.getFileList("get", item)
        }
      },


      // 地址输入框匹配
      pathQuerySearch(queryString, cb) {
        let restaurants = this.allPath;
        // console.log(restaurants)
        let results = queryString ?
          restaurants.filter(this.createFilter(queryString)) :
          restaurants;
        this.matched_path = results.length > 0;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return restaurant => {
          return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
            0
          );
        };
      },

      // 根据文件类型显示图标
      fileTypeIcon(row) {
        let _path = "";
        // 文件夹
        if (row.is_folder) {
          _path = row.isLock ?
            require("./images/file_automatic@3x.png") :
            require("./images/folder@3x.png");
          return _path;
        }
        // 其他根据后缀类型
        let _suffix = row.suffix_name;
        if (!_suffix) {
          _path = require("./images/file_none@3x.png");
          return _path;
        }
        if (["jpg", "jpeg", "png", "gif", "bmp", "JPG"].includes(_suffix)) {
          // 图片
          _path = require("./images/file_img@3x.png");
        } else if (["zip", "rar", "7z"].includes(_suffix)) {
          _path = require("./images/file_zip@3x.png");
        } else if (
          ["avi", "mp4", "rmvb", "flv", "mov", "m2v", "mkv"].includes(_suffix)
        ) {
          _path = require("./images/file_video@3x.png");
        } else if (["mp3", "wav", "wmv", "wma"].includes(_suffix)) {
          _path = require("./images/file_mp3@3x.png");
        } else if (["xls", "xlsx"].includes(_suffix)) {
          _path = require("./images/file_excel@3x.png");
        } else if (["doc", "docx"].includes(_suffix)) {
          _path = require("./images/file_docx@3x.png");
        } else if ("pdf" == _suffix) {
          _path = require("./images/file_pdf@3x.png");
        } else if ("ppt" == _suffix) {
          _path = require("./images/file_ppt@3x.png");
        } else if ("txt" == _suffix) {
          _path = require("./images/file_txt@3x.png");
        } else {
          _path = require("./images/file_none@3x.png");
        }
        return _path;
      },
      // 记录多选列表数据
      filrChecked(val) {
        this.file_checked_data = val
      },
      // 列表模式记录多选数据
      listItemCheck(check, val) {
        this.$refs["wl-table"].toggleRowSelection(val);
      },
      // 清空关键词
      clearSearchKey() {
        this.file.key = "";
      },


      //设置父组件的列表的值
      set_file_table_data(val) {
        this.$parent.file_table_data = val
        // this.file_table_data = val
      },

    },
    computed: {
      // 当前是否第一步
      pathIsStart() {
        if (this.path.index <= 0) {
          this.file.path = ""
        }
        return (
          this.path.index <= 0
        );
      },
      // 当前是否最后一步
      pathIsEnd() {
        this.path.history.length
        this.path.index == (this.path.history.length - 1)
        return this.path.history.length == 1 || (this.path.index == this.path.history.length - 1);
      },
      //是否显示弹框
      showModal() {
        return this.$store.state.showModal
      },
      //显示弹框类型
      modalStatus() {
        return this.$store.state.modalStatus
      },
    },

  };

</script>

<style scoped>
  @import "./util/wl-explorer.css";

  .wl-header-file>>>.el-input.is-disabled .el-input__inner {
    background-color: #ffffff;
    color: #606266;
  }

</style>
